package com.jsoft.android.as;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

// http://www.anddev.org/building_an_android_filebrowser_list-based_-t67.html
// is that built on an early version of android?

public class FP extends ListActivity {

	private List<String> directoryEntries = new ArrayList<String>();
	private File currentDirectory = null; //new File("/");
	
	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;
	
	static final int DIALOG_OPEN_DIRECTORY_ID = 0;
	static final int DIALOG_SHOW_FILE_ID = 1;
	
	Bundle mExtras = null;
	
	String mStatusReturn = "unknown file";
	


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/*
    	 * Make sure we have something we can use
    	 * http://developer.android.com/guide/topics/data/data-storage.html
    	 */
    	String state = Environment.getExternalStorageState();

    	if (Environment.MEDIA_MOUNTED.equals(state)) {
    	    // We can read and write the media
    	    mExternalStorageAvailable = mExternalStorageWriteable = true;
    	} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    	    // We can only read the media
    	    mExternalStorageAvailable = true;
    	    mExternalStorageWriteable = false;
    	} else {
    	    // Something else is wrong. It may be one of many other states, but all we need
    	    //  to know is we can neither read nor write
    	    mExternalStorageAvailable = mExternalStorageWriteable = false;
    	}
    	
    	if (mExternalStorageAvailable && mExternalStorageWriteable) {
    		File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath());
            currentDirectory = dir;
            mStatusReturn = currentDirectory.getName();
    	}
    	
    	// fn is not used yet
    	String fn = "unknown.txt";
        //Bundle extras = getIntent().getExtras();
    	mExtras = getIntent().getExtras();
        if (mExtras != null) {
                String extrasFN = mExtras.getString("fileName");  // ExtraKey
                if (extrasFN != null) {
                	fn = extrasFN;
                }
        }

		browseTo(currentDirectory);
        
	}
	
	
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog = null;
	    switch(id) {
	    case DIALOG_OPEN_DIRECTORY_ID:
	        // do the work to define the pause Dialog
	    	return new AlertDialog.Builder(this)
            //.setIconAttribute(android.R.attr.alertDialogIcon)
            //.setTitle(R.string.alert_dialog_two_buttons_title)
            //.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            .setPositiveButton("Open Directory", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked OK so do some stuff */
                }
            })
            .setNegativeButton("Return directory", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	//Toast.makeText(getApplicationContext(), whichButton, Toast.LENGTH_SHORT).show();
                	done();

                    
                }
            })
            .create();

	    case DIALOG_SHOW_FILE_ID:
	        // 
	    	return new AlertDialog.Builder(this)
            //.setIconAttribute(android.R.attr.alertDialogIcon)
            //.setTitle(R.string.alert_dialog_two_buttons_title)
            //.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            .setPositiveButton("Return file Uri?", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	try {
						// Lets start an intent to View the file, that was clicked...
						//Builder a = new Uri.Builder().path("tel:123");
						//Builder a = new Uri.Builder().path("/mnt/sdcard/test/unknown.txt");
						
						//mStatusReturn = "/mnt/sdcard/test/test.txt";
						
						//Builder a = new Uri.Builder().path("file://");
						
						//Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
						//Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW, a.build());
									//	+ aDirectory.getAbsolutePath()));
						//startActivity(myIntent);
                		done();
					} catch (Exception e) { // URISyntaxException
						e.printStackTrace();
					}
				}})
            .setNegativeButton("Do nothing?", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	//Toast.makeText(getApplicationContext(), whichButton, Toast.LENGTH_SHORT).show();

                    
                }
            })
            .create();
	        // break;
	    default:
	        dialog = null;
	    }
	    return dialog;
	}
	
	/**
	 * This function browses up one level 
	 * according to the field: currentDirectory
	 */
	private void upOneLevel(){
		if(this.currentDirectory.getParent() != null)
			this.browseTo(this.currentDirectory.getParentFile());
	}
	
	private void browseTo(final File aDirectory){
		if (aDirectory.isDirectory()){
			showDialog(DIALOG_OPEN_DIRECTORY_ID);
			this.currentDirectory = aDirectory;
			fill(aDirectory.listFiles());
		}else{
			mStatusReturn = aDirectory.getAbsolutePath();
			showDialog(DIALOG_SHOW_FILE_ID);
		}
	}

	private void fill(File[] files) {
		this.directoryEntries.clear();
		
		// Add the "." and the ".." == 'Up one level'
		// not sure why sleeping
		try {
			Thread.sleep(10);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		this.directoryEntries.add(".");
		
		if(this.currentDirectory.getParent() != null)
			this.directoryEntries.add("..");
		
		for (File file : files){
			this.directoryEntries.add(file.getPath());
		}
		
		ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
				R.layout.list_item, this.directoryEntries);
		
		this.setListAdapter(directoryList);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		String selectedFileString = this.directoryEntries.get(position);
		if (selectedFileString.equals(".")) {
			// Refresh
			this.browseTo(this.currentDirectory);
		} else if(selectedFileString.equals("..")){
			this.upOneLevel();
		} else {
			File clickedFile =  new File(this.directoryEntries.get(position));
			if(clickedFile != null)
				mStatusReturn = clickedFile.getName();
				this.browseTo(clickedFile);
		}
	}

	private void done() {
        Bundle bundle = new Bundle();
    	bundle.putCharSequence("APP_INVENTOR_RESULT", mStatusReturn);
   	    Intent mIntent = new Intent();
        mIntent.putExtras(bundle);
        setResult(RESULT_OK, mIntent);
        
        finish();

		
	}
}